<template>
  <!-- 签名表格弹窗 -->
  <el-dialog
    v-model="showTableDialog"
    :before-close="handleCloseTableDialog"
    title="签名管理"
    width="1100px"
  >
    <el-table
      v-loading="loading"
      :data="signatureData"
      border
      style="width: 100%"
      :span-method="spanMethod"
    >
      <!-- 报告名称列 -->
      <el-table-column align="center" label="报告名称" prop="reportName" width="200" />

      <!-- 签署身份列 -->
      <el-table-column align="center" label="签署身份" width="150">
        <template #default="{ row }">
          <el-select v-model="row.signRole" placeholder="请选择身份">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.SIGN_TYPE).filter((option) =>
                getResultArrayForRow(row)?.includes(option.value)
              )"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </template>
      </el-table-column>

      <!-- 签字人姓名列 -->
      <el-table-column align="center" label="签字人姓名" width="160">
        <template #default="{ row }">
          <div class="signer-name-container">
            <el-input v-model="row.signName" class="signer-input" placeholder="请输入签字人姓名" />
          </div>
        </template>
      </el-table-column>

      <!-- 签字区列 -->
      <el-table-column align="center" label="签字区">
        <template #default="{ row }">
          <div
            :class="{ 'has-signature': !!row.sign }"
            class="signature-area"
            @click="handleSign(row)"
          >
            <img v-if="row.sign" :src="row.sign" alt="签名" class="signature-img" />
            <div v-else class="signature-placeholder">
              <span class="signature-text">点击签名</span>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 签名时间列 -->
      <el-table-column align="center" label="签名时间" width="160">
        <template #default="{ row }">
          <el-date-picker
            v-model="row.signTime"
            format="YYYY-MM-DD"
            placeholder="选择签名时间"
            style="width: 100%"
            type="date"
            value-format="YYYY-MM-DD"
          />
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column align="center" label="操作" width="170">
        <template #default="{ row }">
          <div class="operation-buttons">
            <!--              <el-button link size="small" @click="handleSign(row)">签名</el-button>-->
            <el-button link size="small" type="primary" @click="handleSelectUser(row)"
              >选用户</el-button
            >
            <el-button link size="small" type="primary" @click="addCopy(row)"> 新增</el-button>
            <el-button link size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showTableDialog = false">关闭</el-button>
        <el-button type="primary" @click="handleSaveSignatures">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 签名弹窗 -->
  <el-dialog
    v-model="showSignDialog"
    :before-close="handleCloseSignDialog"
    :title="`签名【${currentSignItem?.signName || ''}】`"
  >
    <SignaturePad
      ref="signaturePadRef"
      :model-value="currentSignItem?.sign || ''"
      @save="handleSignConfirm"
      @close-dialog="handleSignCancel"
      :nickname="currentSignItem?.signName || ''"
      :width="810"
      :type="2"
      :projectId="currentSignItem?.projectId || ''"
      :reportType="currentSignItem?.reportType || ''"
      :signRole="currentSignItem?.signRole || ''"
      :id="currentSignItem?.signId || ''"
      :height="450"
    />
  </el-dialog>

  <!-- 用户选择弹窗 -->
  <el-dialog
    v-model="showUserSelectDialog"
    :before-close="handleCloseUserSelectDialog"
    title="选择签字人"
    width="1300px"
  >
    <UserIndex
      :multiple="false"
      :selectable="true"
      confirm-text="选择此用户"
      @cancel="handleCloseUserSelectDialog"
      @select="handleUserSelected"
    />
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import SignaturePad from '@/views/project/list/SignaturePad.vue'
import UserIndex from '@/views/system/user/index.vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { ProjectApi } from '@/api/dk/project'
import { useRoute, useRouter } from 'vue-router'
import * as UserApi from '@/api/system/user'

// 定义签名数据类型
interface SignatureItem {
  projectId: string
  reportType: string
  reportName: string
  signRole: string
  signName: string
  sign: string
  signId: string
  signTime?: string // 签名时间
}

const props = defineProps({
  projectId: String,
  reportType: String
})

// 响应式数据
const signatureData = ref<SignatureItem[]>([])
const showTableDialog = ref(false)
const showSignDialog = ref(false)
const showUserSelectDialog = ref(false)
const loading = ref(false)
const currentSignItem = ref<SignatureItem | null>(null)
const currentSelectingRow = ref<SignatureItem | null>(null)
const route = useRoute()
const router = useRouter()
const signaturePadRef = ref()
const resultMap = ref()

// 计算属性：根据 reportType 生成 resultMap
const resultMapComputed = computed(() => {
  if (!props.reportType) return []

  const reportType = props.reportType
  const result = []

  if (reportType.includes('/')) {
    // 如果包含 /，按 / 分割
    const parts = reportType.split('/')
    parts.forEach(part => {
      if (part.length >= 2) {
        // 整个部分作为 key，最后两个字符作为 value 数组
        const key = part
        const valueChars = part.length >= 2 ?
          part.substring(part.length - 2).split('') :
          [part]
        result.push({ [key]: valueChars })
      }
    })
  } else {
    // 如果不包含 /，直接处理
    if (reportType.length >= 2) {
      const key = reportType
      const valueChars = reportType.substring(2)
      const charSet = valueChars.split('');
      result.push({ [key]: charSet })
    }
  }
  console.log('resultMap:', JSON.stringify( result))
  return result
})

// 根据当前行的 reportType 获取对应的 resultArray
const getResultArrayForRow = (row: SignatureItem) => {
  if (!row.reportType || !resultMap.value) return []

  // 在 resultMap 中查找匹配的项
  const matchedItem = resultMap.value.find((item: any) =>
    Object.keys(item).includes(row.reportType)
  )

  if (matchedItem) {
    return matchedItem[row.reportType] || []
  }

  return []
}
const showDialog = async () => {
  showTableDialog.value = true
  const response = await ProjectApi.getProjectSign(Number(props.projectId), props.reportType)
  const data = response || []

  // 为每个签名项设置默认的签名时间（当天）
  const today = new Date().toISOString().split('T')[0] // 格式：YYYY-MM-DD
  data.forEach((item) => {
    if (!item.signTime) {
      item.signTime = today
    }
  })

  signatureData.value = data

  // 更新 resultMap
  resultMap.value = resultMapComputed.value

}

// 表格行合并方法
const spanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  if (columnIndex === 0) {
    // 报告名称列
    const reportType = row.reportType
    const sameReportRows = signatureData.value.filter((item) => item.reportType === reportType)
    const firstIndex = signatureData.value.findIndex((item) => item.reportType === reportType)

    if (rowIndex === firstIndex) {
      return {
        rowspan: sameReportRows.length,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

// 处理签名
const handleSign = (row: SignatureItem) => {
  console.log('开始签名:', row)
  currentSignItem.value = row
  console.log('当前签名项:',JSON.stringify( currentSignItem.value))
  showSignDialog.value = true
  // signaturePadRef.value.clear()
}

// 处理签名确认
const handleSignConfirm = (signatureDataUrl: string) => {
  console.log('签名确认:', signatureDataUrl)
  if (currentSignItem.value) {
    console.log('当前签名项:', currentSignItem.value)

    // 更新签名数据
    currentSignItem.value.sign = signatureDataUrl
    if (currentSignItem.value.signId) {
      UserApi.updateUserSign({
        ...currentSignItem.value,
        sign: signatureDataUrl
      })
    }

    // 强制更新表格数据以确保响应式更新
    const index = signatureData.value.findIndex((item) => item === currentSignItem.value)
    if (index !== -1) {
      signatureData.value[index].sign = signatureDataUrl
      console.log('签名数据已更新:', signatureData.value[index])
    }

    ElMessage.success('签名成功')
    showSignDialog.value = false
    currentSignItem.value = null
  }
}

// 处理签名取消
const handleSignCancel = () => {
  showSignDialog.value = false
  currentSignItem.value = null
}

// 处理关闭表格弹窗
const handleCloseTableDialog = () => {
  showTableDialog.value = false
}

// 处理关闭签名弹窗
const handleCloseSignDialog = () => {
  showSignDialog.value = false
  currentSignItem.value = null
}

// 处理选择用户
const handleSelectUser = (row: SignatureItem) => {
  currentSelectingRow.value = row
  showUserSelectDialog.value = true
}

// 处理用户选择完成
const handleUserSelected = (user: any) => {
  console.log('选择的用户:', JSON.stringify(user))
  if (currentSelectingRow.value && user) {
    // 更新签字人姓名
    currentSelectingRow.value.signName = user.nickname || user.username
    currentSelectingRow.value.sign = user.sign || user.sign
    currentSelectingRow.value.signId = user.id || user.sign
    ElMessage.success('已选择签字人：' + currentSelectingRow.value.signName)
  }
  handleCloseUserSelectDialog()
}

// 处理关闭用户选择弹窗
const handleCloseUserSelectDialog = () => {
  showUserSelectDialog.value = false
  currentSelectingRow.value = null
}

// 处理保存签名
const handleSaveSignatures = async () => {
  const projectId = props.projectId
  // 这里可以添加保存逻辑，比如发送到后端
  // console.log('保存的签名数据:', JSON.stringify(signatureData.value))
  showTableDialog.value = false
  await ProjectApi.updateProjectSign({
    projectId: projectId,
    signData: signatureData.value,
    reportType: props.reportType
  })
  ElMessage.success('签名保存成功')
}

// 处理复制签名
const addCopy = (row: SignatureItem) => {
  // 创建一个新的行数据，复制当前行的所有信息
  const newRow: SignatureItem = {
    projectId: row.projectId,
    reportType: row.reportType,
    reportName: row.reportName,
    signRole: '',
    signName: '',
    sign: '',
    signId: '',
    signTime: row.signTime
  }

  // 找到当前行在数组中的索引
  const currentIndex = signatureData.value.findIndex((item) => item === row)

  // 在当前行的下一行插入新行
  if (currentIndex !== -1) {
    signatureData.value.splice(currentIndex + 1, 0, newRow)
  } else {
    // 如果找不到当前行，则添加到末尾
    signatureData.value.push(newRow)
  }
}

// 处理删除签名
const handleDelete = async (row: SignatureItem) => {
  try {
    // await ElMessageBox.confirm('确定要删除这一行吗？', '提示', {
    //   confirmButtonText: '确定',
    //   cancelButtonText: '取消',
    //   type: 'warning'
    // })

    // 找到要删除的行的索引
    const index = signatureData.value.findIndex((item) => item === row)
    if (index !== -1) {
      // 从数组中删除这一行
      signatureData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消删除
  }
}
defineExpose({
  showDialog
})
onMounted(async () => {})
</script>

<style lang="scss" scoped>
.signature-area {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 60px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 4px;

  &:hover {
    border-color: #409eff;
  }

  &.has-signature {
    border-color: #67c23a;
    background-color: #f0f9ff;
    cursor: default;

    &:hover {
      border-color: #67c23a;
    }
  }

  .signature-img {
    max-width: 120px;
    max-height: 50px;
    object-fit: contain;
  }

  .signature-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;

    .signature-icon {
      font-size: 20px;
    }

    .signature-text {
      font-size: 12px;
    }
  }
}

:deep(.el-table) {
  .el-table__cell {
    padding: 8px 0;
  }
}

:deep(.el-button) {
  margin: 0 2px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.operation-buttons {
  display: flex;
  gap: 5px;
}
</style>
